﻿using StackExchange.Redis;
using System.Collections.Generic;

namespace InternetSpiderLib.Scenes.UrlHistories
{
    public class RedisUrlHistories : IUrlHistories
    {
        /// <summary>
        /// 历史数据的Key
        /// </summary>
        public string RedisKey { get; set; }

        /// <summary>
        /// 链接字符串
        /// </summary>
        public string RedisConnectString { get; set; }

        /// <summary>
        /// 添加历史
        /// </summary>
        /// <param name="url"></param>
        public void AddHistory(string url)
        {
            if (string.IsNullOrEmpty(url))
                return;

            if (string.IsNullOrEmpty(RedisConnectString))
                throw new KeyNotFoundException(RedisConnectString);

            using (ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect(RedisConnectString))
            {
                var databse = redisClient.GetDatabase();
                databse.SetAdd(RedisKey, url.ToLower());
            }
        }

        /// <summary>
        /// 是否已经存在过了
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public bool Exist(string url)
        {
            if (string.IsNullOrEmpty(url))
                return false;

            if (string.IsNullOrEmpty(RedisConnectString))
                throw new KeyNotFoundException(RedisConnectString);

            using (ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect(RedisConnectString))
            {
                var databse = redisClient.GetDatabase();
                return databse.SetContains(RedisKey, url.ToLower());
            }
        }
    }
}
